import { useCounter } from "@/model/context";
import { activateList, activateListKing, listNotice, pokerUserActivatInfoJ } from "@/service";
import { localStorageGetItem } from "@/utils/localStorage";
import { Button, message, Modal } from "antd";
import React, { useEffect } from "react";
import { useNavigate } from "react-router-dom";

const activeStatus = [
  '准备中',
  '进行中',
  '已结束',
]

export default function Home() {
  const [messageApi, contextHolder] = message.useMessage();
  const navigate: any = useNavigate();
  const { state: { serverId, serverName, serverList } } = useCounter();
  const [data, setData] = React.useState<any>([]);
  const [data2, setData2] = React.useState<any>([]);
  const [homeInfoList, setHomeInfo] = React.useState<any>([]);
  const [isModalOpen, setIsModalOpen] = React.useState(false);
  const [currentNoticeIndex, setCurrentNoticeIndex] = React.useState(0);

  useEffect(() => {
    getActiveList()
    const isFirst = localStorageGetItem('isFirst')
    console.log(isFirst, 'isFirst');
    
    if (!isFirst) {
      setIsModalOpen(true)
      getHomeInfo()
      localStorage.setItem('isFirst', 'true');
    } 
    // else {
    //   localStorage.setItem('isFirst', 'true');
    // }
    
  }, [serverId])

  const getActiveList = async () => {
    const res = await activateList({ serverId: serverId ? serverId : '', runStatus: 1 })
    setData(res)
    const res1 = await activateListKing({ serverId: serverId ? serverId : '', runStatus: 1 })
    setData2(res1)
  }

  const getHomeInfo = async () => {
    const res = await listNotice()
    setHomeInfo(res)
    setCurrentNoticeIndex(0); 
  }

  const selectDetail = (item: any, type: string) => {
    navigate({
      pathname: type === '1' ? "/activeDetail" : '/activeDetail2',
      search: type === '1' ? `?id=${item.id}&taskId=${item?.taskId}&pubPoker1=${item?.pubPoker1}&pubPoker2=${item?.pubPoker2}&endTime=${item?.endTime}
      &activeName=${item?.name}&activeMaxChage=${item?.activeMaxChage}&changePokerBaseNum=${item?.changePokerBaseNum}&changePokerAddNum=${item?.changePokerAddNum}` : `?id=${item.id}&taskId=${item?.taskId}&endTime=${item?.endTime}
      &activeName=${item?.name}`,
    });
  };
  const joinActive = async (item: any) => {
    const res = await pokerUserActivatInfoJ({
      taskId: item?.taskId,
      activateId: item?.id
    })
    if (res?.length > 0) {
      messageApi.success('已成功参加')
      getActiveList()
      selectDetail(item, '1')
    }
  };
  const getServerName = (id: string | number) => {
    const item = serverList?.find(item => item?.id + '' === id)
    return item ? item?.name : ''
  }

  const handleOk = () => {
    setIsModalOpen(false);
  };

  const handleCancel = () => {
    setIsModalOpen(false);
  };
  const goToNextNotice = () => {
    if (currentNoticeIndex < homeInfoList.length - 1) {
      setCurrentNoticeIndex(currentNoticeIndex + 1);
    }
  };

  const goToPrevNotice = () => {
    if (currentNoticeIndex > 0) {
      setCurrentNoticeIndex(currentNoticeIndex - 1);
    }
  };

  return (
    <>
      <div className="homePage">
        {contextHolder}
        <div className="header">卡片小游戏</div>
        <div className="activeList">
          {data?.map((item: any) => {
            return (
              <div className="acitveItem" key={item?.id}>
                {/* <img
                    src="https://pic1.imgdb.cn/item/6479ba20f024cca173a264b1.jpg"
                    alt=""
                  /> */}
                <div className="activeInfo">
                  <div><span>活动名称:</span><span>{item?.name}</span></div>
                  {/* <div><span>活动倒计时:</span><span></span></div> */}
                  <div><span>所属区服:</span><span>{getServerName(item?.serverId)}</span></div>
                  {/* <div><span>玩家参与状态:</span><span></span></div> */}
                  <div><span>当前排名:</span><span>{item?.rank ? item?.rank : "未参加"}</span></div>
                  {/* <div><span>玩家结算后排名:</span><span></span></div> */}
                  <div><span>截止时间:</span><span>{item?.endTime}</span></div>
                </div>
                <div className="activeActive">
                  {
                    item?.isJoin == 1 && <Button type="primary" onClick={() => selectDetail(item, '1')}>
                      查看详情
                    </Button>
                  }
                  {
                    item?.isJoin == 0 && <Button type="primary" onClick={() => joinActive(item)}>
                      我要参加
                    </Button>
                  }
                </div>
              </div>
            );
          })}
        </div>
        <div className="header">投票活动</div>
        <div className="activeList">
          {data2?.map((item: any) => {
            return (
              <div className="acitveItem" key={item?.id}>
                {/* <img
                    src="https://pic1.imgdb.cn/item/6479ba20f024cca173a264b1.jpg"
                    alt=""
                  /> */}
                <div className="activeInfo">
                  <div><span>活动名称:</span><span>{item?.name}</span></div>
                  {/* <div><span>活动倒计时:</span><span></span></div> */}
                  <div><span>所属区服:</span><span>{getServerName(item?.serverId)}</span></div>
                  {/* <div><span>玩家参与状态:</span><span></span></div> */}
                  <div><span>当前排名:</span><span>{item?.rank ? item?.rank : "未参加"}</span></div>
                  {/* <div><span>玩家结算后排名:</span><span></span></div> */}
                  <div><span>截止时间:</span><span>{item?.endTime}</span></div>
                </div>
                <div className="activeActive">
                  {
                    item?.isJoin == 1 && <Button type="primary" onClick={() => selectDetail(item, '2')}>
                      查看详情
                    </Button>
                  }
                  {
                    item?.isJoin == 0 && <Button type="primary" onClick={() => selectDetail(item, '2')}>
                      我要参加
                    </Button>
                  }
                </div>
              </div>
            );
          })}
        </div>
        <Modal
          title="公告"
          open={isModalOpen}
          onOk={handleOk}
          onCancel={handleCancel}
          footer={[
            <Button key="prev" disabled={currentNoticeIndex === 0} onClick={goToPrevNotice}>
              上一条
            </Button>,
            <Button key="next" disabled={currentNoticeIndex === homeInfoList.length - 1} onClick={goToNextNotice}>
              下一条
            </Button>,
            <Button key="close" type="primary" onClick={handleCancel}>
              关闭
            </Button>,
          ]}
        >
          {homeInfoList.length > 0 && (
            <div style={{ maxHeight: 400, overflowY: 'auto', lineHeight: '1.6' }}>
              <p style={{ whiteSpace: 'pre-line', fontSize: '15px', color: '#333' }}>
                {homeInfoList[currentNoticeIndex]?.noticeContent.replace(/\\n/g, '\n')}
              </p>
              <div style={{ textAlign: 'right', marginTop: 10, color: '#888' }}>
                第 {currentNoticeIndex + 1} / {homeInfoList.length} 条
              </div>
            </div>
          )}
        </Modal>
      </div>
    </>
  );
}
